package com.netty.demo.binary.factorial;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.math.BigInteger;

/**
 * @author shengtao
 * @Description:
 * @date 2018/09/10 13:29
 */
public class FactorialServerHandler extends ChannelHandlerAdapter{

    private BigInteger lastMultiplier = new BigInteger("1");
    private BigInteger factorial = new BigInteger("1");

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.printf("Factorial of %,d is: %,d%n", lastMultiplier, factorial);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // Calculate the cumulative factorial and send it to the client.
        BigInteger message = (BigInteger)msg;
        lastMultiplier = message;
        factorial = factorial.multiply(message);
        ctx.writeAndFlush(factorial);
    }
}
